import Vue from 'vue'
export const LOGIN_RULES = { // 登录规则
  phone: [{
    required: true,
    type: 'string',
    message: '手机号不能为空',
  }, {
    type: 'string',
    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
    message: '手机号不正确',
  }],
  code: [{
    required: true,
    type: 'string',
    message: '验证码不能为空',
  }, {
    type: 'string',
    len: 6,
    message: '验证码错误',
  }]
}
export const COMP_PROJECT_BASIC = { // 比赛项目基本信息
  name: [{
    required: true,
    message: '项目名不能为空',
  }],
  compName: [{
    required: true,
    message: '参与比赛不能为空',
  }],
  awardLevel: [{
    required: true,
    message: '获奖等级不能为空',
  }],
  awardTime: [{
    required: true,
    message: '获奖时间不能为空',
  }],
  awardProveUrl: [{
    required: true,
    message: '获奖证明不能为空',
  }],
}
export const COURSE_PROJECT_BASIC = { // 课设基本信息
  courseId: [{
    required: true,
    message: '课程名称不能为空',
  }],
  name: [{
    required: true,
    message: '项目名称不能为空',
  }]
}
export const RULE_PROJECT_FILE = { // 创建项目附件上传
  name: [{
    required: true,
    message: '文件名称不能为空',
  }],
  classify: [{
    required: true,
    message: '文件类型不能为空',
  }],
  price: [{
    type: 'number',
    message: 'Aha币需为数字',
  }],
}
export const RULE_CONTRACT = { // 合同签署
  name: [{
    required: true,
    message: '名字不能为空',
  }],
}

/**
 * 规则校验
 * @param {Object} params 需要校验的参数对象
 * @param {Object} rules 校验规则
 * @param {Boolean} showToast是否展示toast框
 */
export function verifyForm(params, rules, showToast = false) {
  if (!rules) {
    return false
  }
  let passed = true

  for (const key in params) {
    const arr_rule = rules[ key ] || [] // 单个字段校验规则

    const val = params[ key ] // 输入的值

    for (let i = 0; i < arr_rule.length; i++) {
      const rule = arr_rule[ i ]

      if (rule.required && !val) {
        passed = false
      } else if (rule.type && typeof val !== rule.type) {
        passed = false
      } else if (rule.pattern && !rule.pattern.test(val)) {
        passed = false
      } else if (rule.len && val.length !== rule.len) {
        passed = false
      } else if (rule.maxlen && val.length > rule.maxlen) {
        passed = false
      } else if (rule.min && val < rule.min) {
        passed = false
      } else if (rule.max && val > rule.max) {
        passed = false
      }
      /* 不通过直接退出函数 */
      if (!passed) {
        if (showToast) {
          Vue.prototype.$msg(rule.message, false, 1000)
        }
        return false
      }
    }
  }
  return true
}
